<?php

namespace App\Models\Ddaman;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\common\Base;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class Role extends Base
{
    use HasFactory,SoftDeletes;

    protected $table = "sy_role";

    //const CREATED_AT = null;
    //const UPDATED_AT = null;

    protected $fillable = [
        'name','menu_rule','api_rule'
    ];


    public $rule = [
        'name' => 'required|string|between:2,100',
    ];

    public $editRule = [
        'id' => 'required',
        'name' => 'required|string|between:2,100',
    ];

    public $message = [
        'id.required' => '标识必须',
        'name.required' => '名称必须填写',
    ];

    /*
     * 获取列表
     * */
    public function getList( $param = [] )
    {
        $limit = isset($param['limit']) ? $param['limit'] : 20;
        $where = [];

        if (isset($param['keywords']) && $param['keywords']){
            $keywords = trim($param['keywords']);
            $where[] = ['name','like',"%$keywords%"];
        }

        $field = array_merge(['id','created_at','updated_at'],$this->fillable);
        $list = $this->where($where)->select($field)->orderBy('id','desc')->paginate($limit);
        /*$list->transForm(function ($item){
            $item->menu_rule = json_decode($item->menu_rule,true);
            $item->api_rule = json_decode($item->api_rule,true);
            return $item;
        });*/
        return $list;
    }

    /*
     * 保存数据
     * */
    public function changes( $data , $rule)
    {
        $validator = Validator::make( $data ,$rule ,$this->message);
        if($validator->fails()){
            $this->error = $validator->errors()->toMsg();
            return false;
        }

        DB::beginTransaction();
        try {
            //dump($data);die;
            $data ['menu_rule'] = isset($data['menu_rule']) ? json_encode($data['menu_rule']) : [];
            $data ['api_rule'] = isset($data['api_rule']) ? json_encode($data['api_rule']) : [];
            if (isset($data['id']) && $data['id'])
            {
                $upData = $this->stayFillData($this->fillable,$data);
                //dump($upData);die;
                $result = Role::where('id',$data['id'])->update($upData);
                if (!$result){
                    throw new \Exception('编辑产品失败 10001');
                }
                $data['role_id'] = $data['id'];
            }else{
                $result = Role::create($data);
                if (!$result){
                    throw new \Exception('新增产品失败 10001');
                }
                $data['role_id'] = $result->id;
            }

            //保存权限
            /*$result = $this->saveRoleFunction( $data );
            if (!$result){
                throw new \Exception($this->error);
            }*/

            DB::commit();
            return $result;
        }catch (\Exception $exception){
            DB::rollBack();
            $this->error = $exception->getMessage();
            return false;
        }
    }

    /*
     * 保存扣费城市
     * */
    public function saveRoleFunction( $data )
    {
        if (isset($data['function_list']) && is_array($data['function_list']))
        {
            foreach ($data['function_list'] as $key => $item)
            {
                //更新属性
                $fill = [
                    'role_id','function_id'
                ];
                $upData = stayFill($fill,$item);
                $upData['role_id'] = $data['role_id'];
                $info = RoleFunction::where([
                    ['role_id',$upData['role_id']],
                    ['function_id',$upData['function_id']],
                ])->first();
                //更新
                if (!$info){
                    $result = RoleFunction::create($upData);
                    if (!$result){
                        $this->error = "新增失败 10005";
                        return false;
                    }
                }
            }
        }

        return true;
    }



}
